package com.lujianfei.powersearch.ui.sort.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lujianfei.powersearch.database.SearchItemModel
import com.lujianfei.powersearch.utils.Constant
import com.lujianfei.powersearch.utils.DatabindingDiffUtils
import com.orm.SugarRecord
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class SortItemViewModel: ViewModel() {

    val data = arrayListOf<SearchItemModel>()

    var searchItemModel: SearchItemModel? = null

    fun loadData(callback:()->Unit) {
        viewModelScope.launch {
            val resp = withContext(Dispatchers.IO) {
                val searchItemModels = SugarRecord.find(SearchItemModel::class.java, "parentId=? order by name", "${searchItemModel?.id?:Constant.RootId}")
                searchItemModels.sortByDescending { it.sort }
                searchItemModels
            }
            DatabindingDiffUtils.setData(oldList = data, newList = resp)
            callback.invoke()
        }
    }

    fun saveSort(data: List<SearchItemModel>) {
        var index = this.data.size
        data.forEach {
            it.sort = index.toLong()
            it.save()
            index-=1
        }
    }
}